package admin.models;

import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;

import entities.Page;

public class PageModel {
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String prefix = "";

	private static PageModel instance = null;
	
	public static PageModel getInstance() {
		if (instance == null) {
			instance = new PageModel();
		}
		
		return instance;
	}
	
	private PageModel() {
		try {
			ObjectifyService.register(Page.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           //e.printStackTrace();
        }
		
        ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	public Page getPage(String id) {
		Page page = new Page();
		if (cache != null && cache.containsKey(prefix + id)) {
			page = (Page) cache.get(prefix + id);
		} else {
			try {
				page = ofy.get(new Key<Page>(Page.class, id));
				cache.put(prefix + id, page);
			} catch (Exception e) {
				page = null;
			}
		}
		return page;
	}
	
	public void insert(Page page) {
		if (cache != null) {
			cache.put(prefix + page.getId(), page);
		}
		ofy.put(page);
	}
	
	public void delete(Page page) {
		if (cache != null && cache.containsKey(prefix + page.getId())) {
			cache.remove(prefix + page.getId());
		}
		ofy.delete(page);
	}
}
